package com.torlesse.authdemo.controller;

import com.torlesse.authdemo.common.resp.Result;
import com.torlesse.authdemo.pojo.User;
import com.torlesse.authdemo.service.LoginService;
import com.torlesse.authdemo.service.TokenService;
import com.torlesse.authdemo.utlis.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: torlesse-liang
 * @Date: 2022/02/18/22:41
 * @Description:登录控制器
 */
@CrossOrigin
@RequestMapping("/oauth2")
@RestController
public class LoginController {


    @Autowired
    private LoginService loginService;

    @Autowired
    private TokenService tokenService;

    /**
     * 登录
     * @param user
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody User user){
        User user1 = loginService.findUserByUsername(user.getUsername());
        if(BCrypt.checkpw(user.getPassword(),user1.getPassword())){
            user.setId(user1.getId());
            String token = tokenService.getToken(user);
            return new Result(true,20000,"登陆成功",token);
        }else {
            return  new Result(false,20001,"登录失败");
        }
    }

    /**
     * 获取token信息
     * @param token
     * @return
     */
    @GetMapping("/tokenInfo")
    public Result getTokenInfo(@RequestParam("token") String token){
        String tokenInfo = tokenService.getTokenInfo(token);
        return new Result(true,20000,"操作成功",tokenInfo);
    }

    public static void main(String[] args) {
        String salt = BCrypt.gensalt();
        //获取加密密码
        String password = BCrypt.hashpw("123456",salt);
        System.out.println(password);
    }
}
